package org.icedata.dao;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.icedata.dto.Unit;
import org.springframework.stereotype.Repository;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Repository
public class UnitRepository {
    private static final Logger logger = LogManager.getLogger(UnitRepository.class);

    private static UnitRepository instance;

    private final List<Unit> units;

    private UnitRepository() {
        units = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            // 指定 ./units/ 文件夹的路径
            File unitsDirectory = new File("units");
            logger.info("初始化\t开始读取本地目录下的单元文件 " + unitsDirectory.getAbsolutePath());

            if (unitsDirectory.exists() && unitsDirectory.isDirectory()) {
                File[] unitFiles = unitsDirectory.listFiles((dir, name) -> name.endsWith(".json"));
                if (unitFiles != null) {
                    for (File unitFile : unitFiles) {
                        logger.info("初始化\t正在读入单元文件 " + unitFile.getName());
                        Unit unit = objectMapper.readValue(unitFile, Unit.class);
                        units.add(unit);
                    }
                }
            } else {
                logger.warn("初始化\t./units/ 目录不存在或不是一个文件夹");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static UnitRepository getInstance() {
        if (instance == null) {
            synchronized (UnitRepository.class) {
                if (instance == null) {
                    instance = new UnitRepository();
                }
            }
        }
        return instance;
    }

    public List<Unit> getAllUnits() {
        return units;
    }

    public Unit getUnitById(String unitId) {
        for (Unit unit : units) {
            if (unit.getUnitId().equals(unitId)) {
                return unit;
            }
        }
        return null;
    }
}

